package cn.afactory.tygz.ui.fragments;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.harwkin.nb.camera.PageBigImageActivity;
import com.harwkin.nb.camera.album.ImageItem;
import com.harwkin.nb.camera.callback.SelectMoreListener;
import com.harwkin.nb.camera.model.PicsItem;
import com.harwkin.nb.camera.model.PicsItemList;
import com.harwkin.nb.camera.options.CameraOptions;
import com.harwkin.nb.camera.pop.CameraPop;
import com.harwkin.nb.camera.pop.CameraPopListener;
import com.harwkin.nb.camera.type.OpenType;
import com.harwkin.nb.popmenu.adapter.ServiceTypeAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.common.ImageUploadType;
import cn.afactory.tygz.controller.CommunityController;
import cn.afactory.tygz.model.ServiceType;
import cn.afactory.tygz.model.ServiceTypeList;
import cn.afactory.tygz.model.UploadFileInfo;
import cn.afactory.tygz.model.UploadFileInfoList;
import cn.afactory.tygz.net.NetManager;
import cn.afactory.tygz.net.lsn.OnResponseListener;
import cn.afactory.tygz.ui.adapter.SecondGoodsAddImgGridAdapter;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.StringUtils;
import cn.afactory.tygz.ui.base.utils.sns.PhotoData;
import cn.afactory.tygz.ui.base.views.AutoGridView;

/**
 * Created by Kenneth on 15/9/26.
 */
public class SecondGoodsAddFragment  extends cn.afactory.tygz.ui.base.BaseFragment {

    private SecondGoodsAddImgGridAdapter mAdapter;
    private List<PhotoData> mData = new ArrayList<PhotoData>();
    private CommunityController mController ;
    private EditText secondGoodName;
    private EditText secondGoodPrice;
    private TextView secondGoodType;
    private TextView secondGoodOld;
    private EditText secondGoodContract;
    private EditText secondGoodAddress;
    private EditText secondGoodDes;
    private AutoGridView secondGoodPic;

    public static final int MAX_COUNT = 3;
    private int mLastCount = MAX_COUNT;
    private int mTypeId = -1;
    private int mOldId = -1;
    private List<ServiceType> mTypeList = new ArrayList<>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initCameraPop();
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case CommunityController.MSG_GET_SERVICE_TYPE_OK:
                handleServiceType((ServiceTypeList)msg.obj);
                break;
            case CommunityController.MSG_GET_SERVICE_TYPE_KO:
                break;
        }
        super.handleMessage(msg);
    }

    private void handleServiceType(final ServiceTypeList t){
        hideErrorPage(-1);
        if (t.value != null && t.value.size() >= 0) {
            if(t.value.size() == 0){
                return ;
            }
            mTypeList = t.value;
        }
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_second_goods_add, null);
        initView(view);

        mController = new CommunityController(getActivity(),mUIHandler,null);
        mController.loadServiceTypeList(2);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initView(View view) {
        initTitleBar();

        secondGoodName = (EditText)view.findViewById(R.id.add_goods_name);
        secondGoodPrice = (EditText)view.findViewById(R.id.add_goods_price);
        secondGoodType = (TextView)view.findViewById(R.id.add_goods_type);
        secondGoodOld = (TextView)view.findViewById(R.id.add_goods_old);
        secondGoodContract = (EditText)view.findViewById(R.id.add_goods_contract);
        secondGoodAddress = (EditText)view.findViewById(R.id.add_goods_address);
        secondGoodDes = (EditText)view.findViewById(R.id.add_goods_description);
        secondGoodPic = (AutoGridView)view.findViewById(R.id.add_goods_pic);

//        secondGoodName.setText("电视机");
//        secondGoodPrice.setText("10");
//        secondGoodContract.setText("110");
//        secondGoodAddress.setText("公安局");
//        secondGoodDes.setText("很新的");

        mAdapter = new SecondGoodsAddImgGridAdapter(mContext);
        secondGoodPic.setAdapter(mAdapter);
        secondGoodPic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mData.size() != MAX_COUNT && position == mAdapter.getCount() - 1) {
                    mCameraPop.showMenu(secondGoodPic);
                    return;
                }

                if (mAdapter.getItem(position) instanceof PhotoData) {
//                    (PhotoData) mAdapter.getItem(position).  delete
                    ArrayList<PicsItem> data = new ArrayList<PicsItem>();
                    for (PhotoData photoData : mData) {
                        PicsItem picsItem = new PicsItem();
                        picsItem.image = photoData.mLocalUrl;
                        data.add(picsItem);
                    }
                    getActivity().startActivityForResult(PageBigImageActivity.getIntent(mContext, data, position, true, true),
                            PageBigImageActivity.REQ_CHOOSE_MAP);
                }
            }
        });

        secondGoodOld.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showOldDialog();
            }
        });

        secondGoodType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTypeDialog();
            }
        });
    }
    //显示成色选择对话框
    private void showOldDialog(){
        new AlertDialog.Builder(getActivity(),android.R.style.Theme_Holo_Light_Dialog)
                .setTitle("请选择成色")
                .setItems(R.array.choose_second_goods_cs, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        secondGoodOld.setText(getResources().getStringArray(R.array.choose_second_goods_cs)[which]);
                        mOldId = which + 1;
                    }
                })
                .create()
                .show();
    }
    //选择类型对话框
    private void showTypeDialog(){
        if(mTypeList == null || mTypeList.size() == 0){
            return ;
        }
        new AlertDialog.Builder(getActivity(),android.R.style.Theme_Holo_Light_Dialog)
                .setTitle("请选择物品的分类")
                .setAdapter(new ServiceTypeAdapter(getActivity(),R.layout.popup_item,mTypeList,R.drawable.pb_list_item_normal,R.drawable.pb_list_item_press), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ServiceType serviceType = mTypeList.get(which);
                        mTypeId = serviceType.typeId;
                        secondGoodType.setText(serviceType.typeName);
                    }
                })
                .create()
                .show();
    }

    private void initTitleBar() {
        setTitleText("二手物品发布");

        setRightButton("发布", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPublishSecondGoods();
            }
        });
    }

    private void doPublishSecondGoods(){
        String name = secondGoodName.getText().toString();
        String price = secondGoodPrice.getText().toString();
        String phone = secondGoodContract.getText().toString();
        String address = secondGoodAddress.getText().toString();
        String des = secondGoodDes.getText().toString();

        if(StringUtils.isEmpty(name)){
            LocalUtils.showToast(getActivity(),R.string.toast_name_dismiss);
            return ;
        }

        if(StringUtils.isEmpty(price)){
            LocalUtils.showToast(getActivity(),R.string.toast_price_dismiss);
            return ;
        }

        if(mTypeId < 0){
            LocalUtils.showToast(getActivity(),R.string.toast_type_dismiss);
            return ;
        }

        if(mOldId < 0){
            LocalUtils.showToast(getActivity(),R.string.toast_old_dismiss);
            return ;
        }

        if(StringUtils.isEmpty(des)){
            LocalUtils.showToast(getActivity(),R.string.toast_des_dismiss);
            return ;
        }

        if(StringUtils.isEmpty(address)){
            LocalUtils.showToast(getActivity(), R.string.toast_address_dismiss);
            return ;
        }

        if(StringUtils.isEmpty(phone)){
            LocalUtils.showToast(getActivity(),R.string.toast_phone_dismiss);
            return ;
        }

        if(mData != null && mData.size() > 0){
            doUploadImage();
        }else {
            showLoadingView("");
            NetManager.getInstance(getActivity()).doPublishSecondGoods(name,
                    price,
                    mTypeId + "",
                    phone,
                    address,
                    des,
                    mOldId + "",
                    mFileFiledIds,
                    new OnResponseListener<Boolean>() {
                        @Override
                        public void onComplete(boolean isOK, Boolean result, int errorCode, String errorMsg) {
                            hideLoadingView();
                            if(result && isOK){
                                LocalUtils.showToast(getActivity(),"发布成功");
                                if(getActivity() != null) {
                                    getActivity().finish();
                                }
                            }else{
                                LocalUtils.showToast(getActivity(),errorMsg);
                            }
                        }

                        @Override
                        public void onInternError(int errorCode, String errorMessage) {
                            hideLoadingView();
                            LocalUtils.showToast(getActivity(),errorMessage);
                        }
                    });
        }
    }

    private void initData() {

    }

    //添加新图片
    private void doAddNewImage(){
        if(mCameraPop != null) {
//            mCameraPop.showMenu(userPhotoAlbumAdd);
        }
    }

    private CameraPop mCameraPop;
    private String mFileFiledIds = "";
    //初始化图片的菜单项
    private void initCameraPop(){
        mCameraPop = new CameraPop(this, new CameraPopListener() {
            @Override
            public void onCamreaClick(CameraOptions options) {
                options.setOpenType(OpenType.OPEN_CAMERA);
                mCameraPop.process();
            }

            @Override
            public void onPickClick(CameraOptions options) {
                options.setOpenType(OpenType.OPENN_USER_ALBUM).setMaxSelect(mLastCount);
                mCameraPop.process();
            }

            @Override
            public void onDelClick() {

            }
        }, new SelectMoreListener() {
            @Override
            public void onSelectedMoreListener(List<ImageItem> pathList) {
                selectPhotoOk(pathList);
            }
        });
    }

    /**
     * 更新已选图片
     *
     * @param pathList
     */
    private void selectPhotoOk(List<ImageItem> pathList) {
        if (pathList != null) {
            mData.addAll(PhotoData.ImageItem2PhotoData(pathList));
            mLastCount = mLastCount - pathList.size();
        }
        mAdapter.setData(mData);
    }

    public void dealWithPhotoSelectResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == PageBigImageActivity.REQ_CHOOSE_MAP && resultCode == Activity.RESULT_OK){
            PicsItemList t = (PicsItemList)data.getSerializableExtra(PageBigImageActivity.IMAGE_LIST_DATA);
            mData.clear();
            if(PhotoData.PicItem2PhotoData(t.list) != null){
                mData.addAll(PhotoData.PicItem2PhotoData(t.list));
                mLastCount = MAX_COUNT - t.list.size();
            }
            mAdapter.setData(mData);
        }else {
            mCameraPop.forResult(requestCode, resultCode, data);
        }
    }

    /**
     * 上传图片
     */
    private void doUploadImage(){
        showLoadingView("");
        List<String> files = new ArrayList<>();
        for(PhotoData photoData : mData){
            files.add(photoData.mLocalUrl);
        }
        NetManager.getInstance(mContext).doUploadImages(files, ImageUploadType.SECOND_GOODS,
                new OnResponseListener<UploadFileInfoList>() {
                    @Override
                    public void onComplete(boolean isOK, UploadFileInfoList result, int errorCode, String errorMsg) {
                        hideLoadingView();
                        if (isOK && result != null && result.data != null && result.data.size() > 0) {
                            for (UploadFileInfo uploadFileInfo : result.data) {
                                mFileFiledIds = mFileFiledIds + uploadFileInfo.fileId + ",";
                            }
                            if (mFileFiledIds != null && mFileFiledIds.length() > 0) {
                                mFileFiledIds = mFileFiledIds.substring(0,mFileFiledIds.length() - 1);
                                publicSecondGoods();
                            }
                        } else {
                            LocalUtils.showToast(mContext, "图片上传失败！");
                        }
                    }

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        hideLoadingView();
                        LocalUtils.showToast(mContext, errorMessage);
                    }

                });
    }

    public void publicSecondGoods(){
        String name = secondGoodName.getText().toString();
        String price = secondGoodPrice.getText().toString();
        String phone = secondGoodContract.getText().toString();
        String address = secondGoodAddress.getText().toString();
        String des = secondGoodDes.getText().toString();

        NetManager.getInstance(getActivity()).doPublishSecondGoods(name,
                price,
                mTypeId + "",
                phone,
                address,
                des,
                mOldId + "",
                mFileFiledIds,
                new OnResponseListener<Boolean>() {
                    @Override
                    public void onComplete(boolean isOK, Boolean result, int errorCode, String errorMsg) {
                        hideLoadingView();
                        if(result && isOK){
                            LocalUtils.showToast(getActivity(), "发布成功");
                            if(getActivity() != null) {
                                getActivity().finish();
                            }
                        }else{
                            LocalUtils.showToast(getActivity(),errorMsg);
                        }
                    }

                    @Override
                    public void onInternError(int errorCode, String errorMessage) {
                        hideLoadingView();
                        LocalUtils.showToast(getActivity(),errorMessage);
                    }
                });
    }
}

